<!-- 首页 -->
<template>
  <div class="app-container">
    <!-- 欢迎信息 -->
    <el-card class="welcome-card">
      <div class="welcome-info">
        <h2>欢迎使用在线考试系统</h2>
        <p>{{ welcomeMessage }}</p>
      </div>
    </el-card>

    <el-row :gutter="20" class="dashboard-row">
      <!-- 教师面板 -->
      <template v-if="userRole === 'teacher'">
        <el-col :span="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>题库管理</span>
                <el-button
                  type="primary"
                  link
                  @click="$router.push('/question')"
                >
                  查看详情
                </el-button>
              </div>
            </template>
            <div class="card-content">
              <el-statistic :value="statistics.questionCount || 0">
                <template #title>
                  <div style="display: inline-flex; align-items: center">
                    题目总数
                    <el-icon style="margin-left: 4px">
                      <Document />
                    </el-icon>
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>试卷管理</span>
                <el-button type="primary" link @click="$router.push('/exam')">
                  查看详情
                </el-button>
              </div>
            </template>
            <div class="card-content">
              <el-statistic :value="statistics.paperCount || 0">
                <template #title>
                  <div style="display: inline-flex; align-items: center">
                    试卷总数
                    <el-icon style="margin-left: 4px">
                      <EditPen />
                    </el-icon>
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>考试统计</span>
                <el-button type="primary" link @click="$router.push('/record')">
                  查看详情
                </el-button>
              </div>
            </template>
            <div class="card-content">
              <el-statistic :value="statistics.examCount || 0">
                <template #title>
                  <div style="display: inline-flex; align-items: center">
                    考试场次
                    <el-icon style="margin-left: 4px">
                      <List />
                    </el-icon>
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-card>
        </el-col>
      </template>

      <!-- 学生面板 -->
      <template v-else>
        <el-col :span="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>考试记录</span>
                <el-button type="primary" link @click="$router.push('/record')">
                  查看详情
                </el-button>
              </div>
            </template>
            <div class="card-content">
              <el-statistic :value="statistics.examCount || 0">
                <template #title>
                  <div style="display: inline-flex; align-items: center">
                    已参加考试
                    <el-icon style="margin-left: 4px">
                      <List />
                    </el-icon>
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>成绩统计</span>
              </div>
            </template>
            <div class="card-content">
              <el-statistic
                :value="statistics.averageScore || 0"
                :precision="1"
              >
                <template #title>
                  <div style="display: inline-flex; align-items: center">
                    平均分
                    <el-icon style="margin-left: 4px">
                      <TrendCharts />
                    </el-icon>
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>错题本</span>
                <el-button
                  type="primary"
                  link
                  @click="$router.push('/wrong-questions')"
                >
                  查看详情
                </el-button>
              </div>
            </template>
            <div class="card-content">
              <el-statistic :value="statistics.wrongCount || 0">
                <template #title>
                  <div style="display: inline-flex; align-items: center">
                    错题数量
                    <el-icon style="margin-left: 4px">
                      <Warning />
                    </el-icon>
                  </div>
                </template>
              </el-statistic>
            </div>
          </el-card>
        </el-col>
      </template>
    </el-row>

    <!-- 图表展示 -->
    <!-- <el-row :gutter="20" class="dashboard-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>{{
                userRole === "teacher" ? "班级成绩分布" : "个人成绩趋势"
              }}</span>
            </div>
          </template>
          <div
            class="chart-container"
            :ref="userRole === 'teacher' ? distributionChartRef : scoreChartRef"
          ></div>
        </el-card>
      </el-col>
    </el-row> -->
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";
import {
  Document,
  EditPen,
  List,
  TrendCharts,
  Warning,
} from "@element-plus/icons-vue";
import {
  getExamStatistics,
  getClassScoreStatistics,
  getScoreTrend,
} from "@/api/exam";

const userRole = computed(() => localStorage.getItem("userRole"));
const username = computed(() => localStorage.getItem("username"));
const welcomeMessage = computed(() => {
  const hour = new Date().getHours();
  let timeStr = "";
  if (hour < 6) timeStr = "凌晨好";
  else if (hour < 9) timeStr = "早上好";
  else if (hour < 12) timeStr = "上午好";
  else if (hour < 14) timeStr = "中午好";
  else if (hour < 17) timeStr = "下午好";
  else if (hour < 19) timeStr = "傍晚好";
  else timeStr = "晚上好";
  return `${timeStr}，${username.value}！祝您使用愉快。`;
});

const loading = ref(false);
const statistics = ref({
  questionCount: 0,
  paperCount: 0,
  examCount: 0,
  averageScore: 0,
  wrongCount: 0,
});

// 图表实例
let scoreChart = null;
let distributionChart = null;
const scoreChartRef = ref(null);
const distributionChartRef = ref(null);

// 获取统计数据
const getStatistics = async () => {
  try {
    loading.value = true;
    const data  = await getExamStatistics();
    statistics.value = data;
  } catch (error) {
    console.error("获取统计数据失败：", error);
  } finally {
    loading.value = false;
  }
};

// 初始化成绩趋势图
const initScoreChart = async () => {
  if (!scoreChartRef.value) return;

  try {
    const { data } = await getScoreTrend();
    const dates = data.map((item) => item.date);
    const scores = data.map((item) => item.score);

    scoreChart = echarts.init(scoreChartRef.value);
    scoreChart.setOption({
      title: {
        text: "成绩趋势",
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: dates,
        boundaryGap: false,
      },
      yAxis: {
        type: "value",
        name: "分数",
        min: 0,
        max: 100,
      },
      series: [
        {
          name: "得分",
          type: "line",
          data: scores,
          smooth: true,
          symbolSize: 8,
          itemStyle: {
            color: "#409EFF",
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "rgba(64,158,255,0.3)",
              },
              {
                offset: 1,
                color: "rgba(64,158,255,0.1)",
              },
            ]),
          },
        },
      ],
    });
  } catch (error) {
    console.error("获取成绩趋势数据失败：", error);
  }
};

// 初始化分数分布图
const initDistributionChart = async () => {
  if (!distributionChartRef.value) return;

  try {
    const { data } = await getClassScoreStatistics();
    const ranges = ["0-60", "60-70", "70-80", "80-90", "90-100"];
    const counts = ranges.map((range) => data[range] || 0);

    distributionChart = echarts.init(distributionChartRef.value);
    distributionChart.setOption({
      title: {
        text: "班级成绩分布",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        right: 10,
        top: "center",
      },
      series: [
        {
          name: "成绩分布",
          type: "pie",
          radius: ["40%", "70%"],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: "#fff",
            borderWidth: 2,
          },
          label: {
            show: false,
            position: "center",
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: "bold",
            },
          },
          labelLine: {
            show: false,
          },
          data: ranges.map((range, index) => ({
            value: counts[index],
            name: range,
          })),
        },
      ],
    });
  } catch (error) {
    console.error("获取成绩分布数据失败：", error);
  }
};

// 监听窗口大小变化
const handleResize = () => {
  scoreChart?.resize();
  distributionChart?.resize();
};

onMounted(() => {
  getStatistics();
  if (userRole.value === "teacher") {
    initDistributionChart();
  } else {
    initScoreChart();
  }
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  scoreChart?.dispose();
  distributionChart?.dispose();
});
</script>

<style scoped>
.welcome-card {
  margin-bottom: 20px;
}

.welcome-info {
  text-align: center;
}

.welcome-info h2 {
  margin: 0;
  color: #303133;
}

.welcome-info p {
  margin: 10px 0 0;
  color: #606266;
}

.dashboard-row {
  margin-bottom: 20px;
}

.dashboard-card {
  height: 180px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100% - 50px);
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 100%;
  width: 100%;
}
</style>
